package hu.bme.service;

import java.util.Date;

import hu.bme.domain.Icon;
import hu.bme.domain.Position;
import hu.bme.domain.Score;
import hu.bme.domain.Table;
import hu.bme.domain.Table.EndState;
import hu.bme.domain.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GameService 
{
	private int numberOfPlayers=0;
	
	private User circleUser;
	private User crossUser;
	
	private Table table = new Table(10);
	
	private int moves = 0;
	
	public Table move(String userToken, String buttonId)
	{
		System.out.println(userToken+" "+buttonId);
		String splittedPositions[] = buttonId.split(",");
		Position position = new Position().setX(Integer.parseInt(splittedPositions[0])).setY(Integer.parseInt(splittedPositions[1]));
		table.setIconByPosition(position);
		checkWinnerState(position);
		swapCurrentUser(userToken);
		
		moves++;		
		return table;
	}
	
	private void checkWinnerState(Position pos) {

		if(table.checkEndConditions(pos, moves) == EndState.WIN)
		{
			table.setWinner(table.getCurrentRound());
			Score score = new Score();
			score.setUserName(table.getCurrentRound().getId()+new Date().toString());
			score.setRound(moves);
			score.persist();
		}
		else if(table.checkEndConditions(pos, moves) == EndState.DRAW)
		{
			//TODO
		}
		
		
	}

	private void swapCurrentUser(String userToken)
	{
		User newUser;
		
		if(userToken.equals("CIRCLE"))
		{
			newUser = crossUser;
		}
		else
		{
			newUser = circleUser;
		}
		table.setCurrentRound(newUser);
	}
	
	public String generatePlayerToken()
	{
		numberOfPlayers++;
		
		if(numberOfPlayers==1)
		{
			crossUser = new User();
			crossUser.setId("CROSS");
			table.setCurrentRound(crossUser);
			return "CROSS";
		}
		if(numberOfPlayers==2)
		{
			circleUser = new User();
			circleUser.setId("CIRCLE");

			return "CIRCLE";
		}
		reset();

		
		return "NO PLAYER";
	}
	
	public boolean startGameIfTwoPlayerConnected()
	{
		if(numberOfPlayers==2)
		{
			return true;
		}
		return false;
	}
	
	public void reset()
	{
		numberOfPlayers=0;
		table = new Table(10);
		moves = 0;
	}


	public Table getTable() {
		return table;
	}


	public void setTable(Table table) {
		this.table = table;
	}

	public int getMoves() {
		return moves;
	}

	public void setMoves(int moves) {
		this.moves = moves;
	}	
}
